package data.structure.linear.queue.circle;

import java.util.Arrays;

/**
 * @Author douhy
 * @description 手写循环队列（动态数组实现）
 * @date 22/01/25
 */
public class CircleQueue<E> {

    // 动态数组大小
    private int size;

    // int 默认值0
    // 第一个元素位置
    private int front;

    private E[] elements;

    private int DEFAULT_CAPACITY = 10;

    // 构造方法
    public CircleQueue() {
        elements = (E[]) new Object[DEFAULT_CAPACITY];
    }

    // size isEmpty clear deQueue enQueue fornt toString ensureCapacity index

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public void clear() {
        for (int i = 0; i < size; i++) {
            elements[index(i)] = null;
        }
        size = 0;
        front = 0;
    }

    public void enQueue(E element) {
        ensureCapacity(size + 1);
        elements[index(size)] = element;

        size++;
    }

    // 出队逻辑
    // 1.拿到front指向元素返回
    // 2.将front位置元素设置为null
    // 3.将下一个元素设置为front
    // size-- 返回刚开始front指向的元素
    public E deQueue() {
        E frontElement = elements[front];
        elements[front] = null;
        front = index(1);
        size--;
        return frontElement;
    }

    // 循环队列使用 比取余数效率更高
    public int index(int index) {
        index += front;
        return index - (index >= elements.length ? elements.length : 0);
    }

    public E front() {
        return elements[front];
    }

    // 检查容量
    public void ensureCapacity(int capacity) {
        int oldCapacity = elements.length;
        if (oldCapacity >= capacity) return;

        int newCapacity = oldCapacity + (oldCapacity >> 1);
        E[] newElements = (E[]) new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            newElements[i] = elements[index(i)];
        }
        elements = newElements;

        front = 0;
    }

    @Override
    public String toString() {
        return "CircleQueue{" +
                "size=" + size +
                ", front=" + front +
                ", elements=" + Arrays.toString(elements) +
                ", DEFAULT_CAPACITY=" + DEFAULT_CAPACITY +
                '}';
    }
}
